import os
from bs4 import BeautifulSoup
import cssutils

import mistune
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import get_lexer_by_name

class HighlightRenderer(mistune.HTMLRenderer):
    def block_code(self, code, info=None):
        if info:
            lexer = get_lexer_by_name(info, stripall=True)
            formatter = HtmlFormatter()
            return highlight(code, lexer, formatter)
        return f'<pre><code>{mistune.escape(code)}</code></pre>'

def remove_frontmatter(text):
    """
    移除markdown文件头部的frontmatter
    frontmatter格式为：
    ---
    key: value
    ---
    """
    if text.startswith('---'):
        parts = text.split('---', 2)
        if len(parts) >= 3:
            return parts[2].strip()
    return text

def convert_markdown(text):
    # 首先移除frontmatter
    text = remove_frontmatter(text)
    renderer = HighlightRenderer()
    markdown = mistune.create_markdown(renderer=renderer)
    return markdown(text)

def css2style(css_file, html_content):
    """将外部CSS样式转换为内联样式"""
    # 读取CSS文件内容
    with open(css_file, 'r', encoding='utf-8') as f:
        css_content = f.read()

    # 设置cssutils的日志级别为ERROR，忽略警告
    import logging
    cssutils.log.setLevel(logging.ERROR)

    # 解析CSS
    sheet = cssutils.parseString(css_content)
    
    # 解析HTML
    soup = BeautifulSoup(html_content, 'html.parser')
    
    # 处理每个CSS规则
    for rule in sheet:
        if rule.type == rule.STYLE_RULE:
            # 获取选择器和样式
            selector = rule.selectorText
            # 忽略包含伪类的选择器
            if ':' in selector:
                continue
                
            if '.markdown-body' in selector:
                # 移除.markdown-body前缀
                selector = selector.replace('.markdown-body', '').strip()
                if selector:
                    try:
                        # 查找匹配的元素
                        for element in soup.select(selector):
                            # 合并样式
                            existing_style = element.get('style', '')
                            new_style = ';'.join([f"{p.name}:{p.value}" for p in rule.style])
                            element['style'] = f"{existing_style};{new_style}" if existing_style else new_style
                    except Exception as e:
                        print(f"选择器 {selector} 处理失败: {str(e)}")
                        continue

    # 生成完整的HTML文档
    template = f"""<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Markdown Preview</title>
</head>
<body style="max-width: 900px; margin: 0 auto; padding: 30px; font-family: PingFang SC,Microsoft YaHei,sans-serif,OPPOSans2,'Helvetica Neue', Helvetica, Arial, sans-serif;">
    {soup.decode()}
</body>
</html>"""
    
    # 确保输出目录存在
    os.makedirs('static/outs', exist_ok=True)
    
    # 保存文件
    output_path = 'static/outs/tempmd.html'
    with open(output_path, 'w', encoding='utf-8') as f:
        f.write(template)
        
    return output_path
